package com.dl.service.impl;

import com.dl.dao.OrderDao;
import com.dl.pojo.Order;
import com.dl.service.AccountService;
import com.dl.service.OrderService;
import com.dl.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private AccountService accountService;
    @Autowired
    private StorageService storageService;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     * 下订单->扣库存->减余额->改状态，在一个分布式事务中
     * @param order
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public int create(Order order) {
        log.info("------------开始创建订单！------------");
        int result = orderDao.create(order);

        log.info("------------调用库存服务开始扣减库存！------------");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("------------扣减库存结束！------------");

        log.info("------------调用库存服务开始扣减账户！------------");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("------------扣减账户余额结束！------------");

        log.info("------------开始修改订单状态！------------");
        result=orderDao.update(order.getUserId(),0); //0：创建中，1：创建完成
        log.info("------------订单状态修改结束！------------");

        log.info("------------订单交易结束！------------");
        return result;
    }
}
